// pages/test/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isConnected: false,
    isFailed: true,
    deviceName: "AM-F628C3E507D309",
    command: '542d303030314d',
    commandm: 'T-0001M',
    characteristics: "",   // 连接设备的状态值
    writeServicweId: "", // 可写服务uuid
    writeCharacteristicsId: "",//可写特征值uuid
    readServicweId: "", // 可读服务uuid
    readCharacteristicsId: "",//可读特征值uuid
    notifyServicweId: "", //通知服务UUid 
    ALLUUID: "0000FFE0-0000-1000-8000-00805F9B34FB" //同时具有可读、可写、通知三种属性的UUID
            //0000FFE0-0000-1000-8000-00805F9B34FB
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {


    // var ss = this.str2ab16("T-0001M");
    // console.log("ss",ss);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
      this.onCloseConnect();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  conn:function(){
    console.log("开始连接");
   
    let that = this;
    wx.openBluetoothAdapter({
      success: function (res) {
        //if (!that.data.isConnected) {
        that.startBluetoothDevicesDiscovery();
        wx.showLoading({
          title: '搜索中',
        })
        // }
      },
      fail: function (res) {
        wx.showToast({
          title: '请先开启蓝牙',
          icon: 'none',
          duration: 1000
        })
      }
    });
  },
  startBluetoothDevicesDiscovery: function () {
    var that = this;
    wx.startBluetoothDevicesDiscovery({
      success: function (res) {
        console.log("discovery", res);
        if (res.errCode == 0) {
          that.getConnect();
        }
      },
    });
  },
  getConnect: function () {
    var that = this;
    var timer = setInterval(function () {
      wx.getBluetoothDevices({
        success: function (res) {
          console.log("devices", res);
          for (var i = 0; i < res.devices.length; i++) {
            if (res.devices[i].name == that.data.deviceName) {
              wx.hideLoading();
              wx.showLoading({
                title: '连接中',
              })
              that.setData({
                isFinded: true
              });
              clearInterval(timer);
              that.setData({
                deviceId: res.devices[i].deviceId
              });
              console.log('设备号', that.data.deviceId);
              console.log("开始尝试建立连接");
              wx.createBLEConnection({
        
        
        
                deviceId: that.data.deviceId,
                timeout: 10000,
                success: function (res) {
                  console.log(res);
                  if (res.errCode == 0) {
                    console.log('连接成功')
                    that.setData({
                      isConnected: true
                    });
                    wx.stopBluetoothDevicesDiscovery();
                    that.onGetuuid();
                  } else {
                    wx.showModal({
                      title: '提示',
                      content: '不能正常对蓝牙设备进行连接',
                      showCancel: false
                    })
                  }
                },
                fail: (res) => {
                  wx.hideLoading();
                  if (res.errCode == 10012) {
                    wx.showModal({
                      title: '提示',
                      content: '连接超时',
                      showCancel: false
                    })
                  }
                  console.warn("fail", res);
                },
                complete: () => {
                  wx.hideLoading();
                }
              })
              break;
            }
          }
        }
      });
    },
      3000);
    setTimeout(function () {
      if (!that.data.isFinded && !that.data.isConnected) {
        clearInterval(timer);
        that.setData({
          isFailed: false
        });
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '搜索蓝牙超时',
          showCancel: false
        })
      }
    }, 12000);
  },
  onGetuuid() {
    let that = this;
    //that.onConnect();
    if (that.data.isConnected && that.data.isFailed) {
      wx.showLoading({
        title: '获取serviceId',
      })
      console.log("开始获取设备信息,获取serviceId");
      wx.getBLEDeviceServices({
        deviceId: that.data.deviceId,
        success(getServicesRes) {
          console.log("getServicesRes", getServicesRes);
          let service = getServicesRes.services[1]
          let serviceId = that.data.ALLUUID
          wx.showLoading({
            title: '获取characteristicId',
          })

          console.log("deviceId",that.data.deviceId);
          console.log("serviceId",serviceId);
          wx.getBLEDeviceCharacteristics({
            deviceId: that.data.deviceId,
            serviceId: serviceId,
            success: function (res) {
              console.log("成功的开始",res.characteristics);
              for (var i = 0; i < res.characteristics.length; i++) {
                console.log('特征值：' + res.characteristics[i].uuid)
                if (res.characteristics[i].properties.notify) {
                  console.log("获取开启notify的ServicweId：", serviceId);
                  console.log("获取开启notify的CharacteristicsId：", res.characteristics[i].uuid);
                  that.setData({
                    notifyServicweId: serviceId,
                    notifyCharacteristicsId: res.characteristics[i].uuid,
                  })
                }
                if (res.characteristics[i].properties.write) {
                  console.log("获取开启write的ServicweId：", serviceId);
                  console.log("获取开启write的CharacteristicsId：", res.characteristics[i].uuid);
                  that.setData({
                    writeServicweId: serviceId,
                    writeCharacteristicsId: res.characteristics[i].uuid,
                  })
                } else if (res.characteristics[i].properties.read) {
                  console.log("读read操作readServicweId：", serviceId);
                  console.log("读read操作：readCharacteristicsId", res.characteristics[i].uuid);
                  that.setData({
                    readServicweId: serviceId,
                    readCharacteristicsId: res.characteristics[i].uuid,
                  })

                }
              }
              console.log('!!!!!!!!!!!!!!!!!!!!!!!!!!!:', res.characteristics);
              that.startnotify();
            },
            fail: (res) => {
              console.warn("获取特征值信息失败", res);
            },
            complete: (res) => {
              console.log('获取服务信息完成', res);
              wx.hideLoading();
            }
          })
        },
        fail: (res) => {
          console.warn("获取服务信息失败", res);
        },
        complete: () => {
          wx.hideLoading();
        }
      })
    } else {
      wx.showToast({
        title: '请先连接蓝牙',
      })
    }
  },
  start() {
   
    
  },
  str2ab(str) {
    console.log(str)
    var buf = new ArrayBuffer(str.length);
    var bufView= new Uint8Array(buf);
    for (var i = 0, strLen = str.length; i < strLen; i++) {
      bufView[i] = str.charCodeAt(i)
    }

    console.log(bufView)
    console.log('999*',buf)
    return buf
  },
  ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    })
    return hexArr.join('');
  },
  startnotify() {
    var that = this;
    var notifyServicweId = that.data.ALLUUID//具有读、写、通知、属性的服务uuid
    var notifyCharacteristicsId = that.data.notifyCharacteristicsId;
    console.log("启用notify的serviceId", notifyServicweId);
    console.log("启用notify的notifyCharacteristicsId", notifyCharacteristicsId);
    wx.notifyBLECharacteristicValueChange({
      state: true, // 启用 notify 功能
      // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
      deviceId: that.data.deviceId,
      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
      serviceId: notifyServicweId,
      // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
      characteristicId: that.data.notifyCharacteristicsId,

      success: function (res) {
        console.log('notifyBLECharacteristicValueChange success', res.errMsg)
        var msg = '启动通知notify返回:' + res.errMsg
        that.onSendCommand();
        that.setData({
          motto: msg
        })

      },
      fail: function (res) {
        console.log(res.errMsg);
        console.log(that.data.notifyServicweId);
        console.log(that.data.notifyCharacteristicsId);
      },
    })
  },
   buf2hex(buffer) {

    return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
  
  },
  onSendCommand() {
   
    let that = this;
    var ss = "T-0001M";
    var buffer =  that.str2ab(ss);
    console.log("测试", that.data.ALLUUID,that.data.writeCharacteristicsId)

    if (that.data.ALLUUID && that.data.writeCharacteristicsId) {
      wx.writeBLECharacteristicValue({
        deviceId: that.data.deviceId,
        serviceId: "0000FFE0-0000-1000-8000-00805F9B34FB",
        // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
        characteristicId: "0000FFE1-0000-1000-8000-00805F9B34FB",
        value:  buffer,
        success: function (res) {
          console.log("buffer", buffer);
          console.log("发送指令成功");
        
        },
        fail: function (res) {
          console.warn("发送指令失败", res);
          that.setData({ motto: "发送指令失败" + res.errMsg });
        }
      })
    } else {
      that.onConnect();
      wx.showModal({
        title: '提示',
        content: '请先获取设备信息',
        showCancel: false
      })
    }
  },
  onCloseConnect() {
    this.setData({
      isConnected: false,
      isFinded: false
    })
    wx.closeBLEConnection({
      deviceId: this.data.deviceId,
      success: function (res) {
        console.log("成功断开连接");
        // wx.showToast({
        //   title: '成功断开连接',
        // })
      },
    })
  }
})